import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo


__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
           'resnet152']


# ResNet的ImageNet pretrained权重的链接
model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}

# --------------------- 基础模块 -----------------------
# in_planes: 输入特征图的通道数
# out_planes: 输出特征图的通道数
# stride: 卷积的步长
def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    # 2D卷积
    # 卷积核大小3*3，步长为stride，填充为1
    # 不使用偏置项，为了何配合BatchNorm层使用
    # 偏置项是卷积层中一个可学习的参数，output = conv(input) + bias
    # 但是BatchNorm层中也有一个可学习的参数gamma和beta，output = gamma * (input - mean) / std + beta
    # 所以偏置项可以被吸收到BatchNorm层中，所以不使用偏置项
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

def conv1x1(in_planes, out_planes, stride=1):
    """1x1 convolution"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)

# ResNet基本残差块
# conv3x3 -> BN -> ReLU -> conv3x3 -> BN
# 在ResNet中，多个BasicBlock会串联起来
# 每个block的输入都是上一个block的输出
class BasicBlock(nn.Module):
    expansion = 1 # 扩展系数，用于调整输出通道数

    # inplanes: 输入特征图的通道数
    # planes: 输出特征图的通道数
    # stride: 卷积的步长
    # downsample: 下采样层，用于调整特征图的尺寸
    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride) # 第一个3*3卷积
        self.bn1 = nn.BatchNorm2d(planes) # 第一个BatchNorm层
        self.relu = nn.ReLU(inplace=True) # ReLU激活函数
        self.conv2 = conv3x3(planes, planes) # 第二个3*3卷积
        self.bn2 = nn.BatchNorm2d(planes) # 第二个BatchNorm层
        self.downsample = downsample # 下采样层
        self.stride = stride # 卷积的步长

    # 为什么需要下采样层
    # 在ResNet中，每个残差块都有残差连接（out += identity）
    # 当特征图的尺寸发生变化时（比如通过stride>1的卷积），输入和输出的维度可能不匹配
    # 为了能够进行残差连接，需要将输入调整到与输出相同的维度

    # 前向传播
    # x是输入特征图的张量，形状为[B, C, H, W] B：batch_size，C：通道数，H：高度，W：宽度
    def forward(self, x):
        identity = x # 保存输入x作为残差连接

        # 第一个卷积块 3*3卷积
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        # 第二个卷积块 3*3卷积
        out = self.conv2(out)
        out = self.bn2(out)

        # 如果需要下采样，则使用下采样层调整特征图的尺寸
        if self.downsample is not None:
            identity = self.downsample(x)

        # 残差连接：将原始输入叠加到卷积结果上
        out += identity
        out = self.relu(out)

        return out
    

# ResNet中的Bottleneck残差块
# 先压缩维度，在低维空间计算，最后恢复原始维度，像一个瓶颈结构。
# conv1x1 -> BN -> ReLU -> conv3x3 -> BN -> ReLU -> conv1x1 -> BN
class Bottleneck(nn.Module):
    expansion = 4 # 扩展系数，用于调整输出通道数

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = conv1x1(inplanes, planes) # 降维，inplanes -> planes
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = conv3x3(planes, planes, stride) # 在低维空间进行计算
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = conv1x1(planes, planes * self.expansion)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        identity = x

        # 第一个卷积块 1*1卷积
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        # 第二个卷积块 3*3卷积
        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        # 第三个卷积块 1*1卷积
        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            identity = self.downsample(x)

        out += identity
        out = self.relu(out)

        return out
# Bottleneck主要用于更深的网络（如ResNet50/101/152）
# 通过1x1卷积先降维再升维，减少参数量和计算量
# 中间的3x3卷积在低维空间进行，计算更高效
# 例子：inplanes=256, planes=64
    # 降维过程：第一个1*1卷积，256 -> 64
    # 中间处理：3*3卷积，64*64，在低维空间进行计算更高效
    # 升维过程：第二个1*1卷积，64*64 -> 256

# BasicBlock和Bottleneck的对比
# 假设输入通道为256，输出通道为256
    # Bottleneck参数量：
    # 1x1(256->64) + 3x3(64->64) + 1x1(64->256) = 256*64 + 64*64*9 + 64*256 = 69632
   
    # BasicBlock参数量：
    # 3x3(256->256) + 3x3(256->256) = 256*256*9 + 256*256*9 = 1179648
# 使用场景
    # BasicBlock：用于较浅的网络（ResNet18/34）
    # Bottleneck：用于较深的网络（ResNet50/101/152）
# Bottleneck是BasicBlock的优化版本
# 通过1x1卷积的降维和升维操作，在保持网络性能的同时显著减少了参数量和计算量，特别适合构建更深的网络。
# 这两种结构的选择主要取决于网络的深度和计算资源的限制。

# --------------------- ResNet网络 -----------------------
class ResNet(nn.Module):
    # block 使用的残差块模型（BasicBlock或Bottleneck）
    # layers 每个stage的残差块数量
    # zero_init_residual 是否使用0初始化最后一个BN层
    def __init__(self, block, layers, zero_init_residual=False):
        super(ResNet, self).__init__()
        self.inplanes = 64
        # 卷积层 输入通道3，输出通道64，卷积核大小7*7，步长2，填充3
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
        # 批归一化层 输入通道64，输出通道64
        self.bn1 = nn.BatchNorm2d(64)
        # ReLU激活函数，inplace=True表示原地操作，节省内存
        self.relu = nn.ReLU(inplace=True)
        # 最大池化，池化核大小3*3，步长2，填充1
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        # 构建ResNet的4个stage
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)

        # 参数初始化
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                # 使用Kaiming初始化卷积层权重
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                # 初始化BN层的权重和偏置
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)

        # 如果zero_init_residual为True，则使用0初始化最后一个BN层
        # 这样每个残差分支从0开始，每个残差块的行为就像一个恒等映射
        # Zero-initialize the last BN in each residual branch,
        # so that the residual branch starts with zeros, and each residual block behaves like an identity.
        # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677
        if zero_init_residual:
            for m in self.modules():
                if isinstance(m, Bottleneck):
                    nn.init.constant_(m.bn3.weight, 0)
                elif isinstance(m, BasicBlock):
                    nn.init.constant_(m.bn2.weight, 0)

    # 构建每个stage的残差块
    # block: 残差块模型（BasicBlock或Bottleneck）
    # planes: 输出通道数
    # blocks: 残差块数量
    # stride: 卷积步长
    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        # 处理维度不匹配的情况
        # 如果stride不为1，或者输入通道数不等于输出通道数乘以扩展系数
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                conv1x1(self.inplanes, planes * block.expansion, stride),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for _ in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        """
        Input:
            x: (Tensor) -> [B, C, H, W]
        Output:
            c5: (Tensor) -> [B, C, H/32, W/32]
        最大降采样倍数：32。输入图像416*416，输出特征图13*13.
        """
        c1 = self.conv1(x)     # [B, C, H/2, W/2]
        c1 = self.bn1(c1)      # [B, C, H/2, W/2]
        c1 = self.relu(c1)     # [B, C, H/2, W/2]
        c2 = self.maxpool(c1)  # [B, C, H/4, W/4]

        c2 = self.layer1(c2)   # [B, C, H/4, W/4]
        c3 = self.layer2(c2)   # [B, C, H/8, W/8]
        c4 = self.layer3(c3)   # [B, C, H/16, W/16]
        c5 = self.layer4(c4)   # [B, C, H/32, W/32]

        return c5


# --------------------- 构建ResNet网络的函数 -----------------------
## 搭建ResNet-18网络
def resnet18(pretrained=False, **kwargs):
    """搭建 ResNet-18 model.

    Args:
        pretrained (bool): 如果为True，则加载imagenet预训练权重
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    if pretrained:
        # 加载预训练权重
        # strict = False as we don't need fc layer params.
        # 不严格要求加载预训练权重，因为我们不需要最后的全连接层参数
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']), strict=False)
    return model

## 搭建ResNet-34网络
def resnet34(pretrained=False, **kwargs):
    """搭建 ResNet-34 model.

    Args:
        pretrained (bool): 如果为True，则加载imagenet预训练权重
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']), strict=False)
    return model

## 搭建ResNet-50网络
def resnet50(pretrained=False, **kwargs):
    """搭建 ResNet-50 model.

    Args:
        pretrained (bool): 如果为True，则加载imagenet预训练权重
    """
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet50']), strict=False)
    return model

## 搭建ResNet-101网络
def resnet101(pretrained=False, **kwargs):
    """搭建 ResNet-101 model.

    Args:
        pretrained (bool): 如果为True，则加载imagenet预训练权重
    """
    model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet101']), strict=False)
    return model

## 搭建ResNet-152网络
def resnet152(pretrained=False, **kwargs):
    """搭建 ResNet-152 model.

    Args:
        pretrained (bool): 如果为True，则加载imagenet预训练权重
    """
    model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
    return model

## 搭建ResNet网络
def build_backbone(model_name='resnet18', pretrained=False):
    if model_name == 'resnet18':
        model = resnet18(pretrained)
        feat_dim = 512    # 网络的最终输出的feature的通道维度为512
    elif model_name == 'resnet34':
        model = resnet34(pretrained)
        feat_dim = 512    # 网络的最终输出的feature的通道维度为512
    elif model_name == 'resnet50':
        model = resnet34(pretrained)
        feat_dim = 2048   # 网络的最终输出的feature的通道维度为2048
    elif model_name == 'resnet101':
        model = resnet34(pretrained)
        feat_dim = 2048   # 网络的最终输出的feature的通道维度为2048

    return model, feat_dim


if __name__=='__main__':
    # 这是一段测试代码，方便读者测试能否正常的下载ResNet权重和调用ResNet网络
    model, feat_dim = build_backbone(model_name='resnet18', pretrained=True)

    # 打印模型的结构
    print(model)

    # 输入图像的参数
    batch_size    = 2
    image_channel = 3
    image_height  = 512
    image_width   = 512

    # 随机生成一张图像
    image = torch.randn(batch_size, image_channel, image_height, image_width)

    # 模型推理
    output = model(image)

    # 查看模型的输出的shape
    print(output.shape)

# 关于 nn.Module
    # nn.Module自动追踪所有子模块和参数
    # 参数通过名称和形状匹配
    # 预训练权重可以部分加载
    # 支持自定义参数初始化
# 使用场景
    # 迁移学习
    # 模型微调
    # 参数共享
    # 模型保存和加载
# 模型初始化时调用的super方法
    # super(BasicBlock, self).__init__() 
    # 作用
        # nn.Module维护了一个有序字典_modules来存储子模块
        # 需要初始化这个字典和其他必要的属性
        # 确保参数追踪、梯度计算等功能正常工作
    # 如果去掉
        # 无法正确追踪模型参数
        # 无法进行梯度计算
        # 无法保存和加载模型
        # 无法使用预训练权重
    # 在PyTorch中的重要性：
        # 是构建神经网络模块的必要步骤
        # 确保模块能够正确参与前向传播和反向传播
        # 保证参数能够被正确初始化和更新
    # 所以，这行代码是构建PyTorch神经网络模块的基础，确保模块能够正常工作，是绝对不能省略的。